var cp = require('child_process');
var db = require('../database/mongo_database.js');
var fs = require('fs');
var mail = require('./excel_mail.js');

var exec_excel_builder = function (exe_record,req, res) {
    var exefile = exe_record.value;
    console.log(exefile);

    if (fs.existsSync(exefile)) {
        var line = exefile + " " + req.params.user_id + " " + req.params.date;
        
        var excel = cp.exec(line);

        excel.stdout.on('data', function (data) {
            console.log('stdout: ' + data);
        });
        
        excel.stderr.on('data', function (data) {
            console.log('stderr: ' + data);
            res.send(206, "error");
            return next(data);
        });
        
        excel.on('exit', function (code) {
            if (code == 0) {
                console.log("[excel success] " + req.params.user_id + " " + req.params.date);
                mail.sendmail(req.params.user_id, req.params.date, function (info) {
                    res.send(200, 'ok');
                    return next(info);
                });
           
            } else {
                console.log("[excel error] " + req.params.user_id + " " + req.params.date);
                res.send(206, "error");
                return next(code);
            }
        });
    }else{
        res.send(207, "exe file not found");
        return next(code);
    }
}

exports.do_excel = function (req, res, next) {
    
    //res.setHeader('Access-Control-Allow-Origin', '*');
    
    db.settings.findOne({ 'name': 'excel_generater_path' }, function (err, success) {
        
        if (success) {
            return exec_excel_builder(success, req, res);
        } else {
            res.send(208,'excel_generater_path not in TABLE: settings');
            return next(err);
        }

    });

}


